//
//  TestViewController.swift
//  EngineTestIOS
//
//  Created by 张海南 on 2023/4/18.
//

import UIKit
// 1. 引入库
import FlutterPluginRegistrant

class TestFlutterViewController: FlutterViewController {
    
    private var channel: FlutterMethodChannel?

    init(withEntrypoint entryPoint: String?) {
        let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
        // 1. 用Appdelegate中的FlutterEngineGroup生成一个FlutterEngine，引擎加载入口是main.dart的entrypoint函数
        let newEngine = appDelegate.engineGroup.makeEngine(withEntrypoint: entryPoint, libraryURI: nil)
        // 2. 用这个FlutterEngine初始化FlutterViewController
        super.init(engine: newEngine, nibName: nil, bundle: nil)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 2. 注册插件到FlutterEngine中
        GeneratedPluginRegistrant.register(with: self.pluginRegistry())
        
        // 1. 生成FlutterMethodChannel
        channel = FlutterMethodChannel(name: "tab_switch", binaryMessenger: self.engine!.binaryMessenger)
        // 2. 注册回调方法
        channel?.setMethodCallHandler({ [weak self] call, result in
            if call.method == "showTab" {
                // 3. 显示TabBar
                self?.showTab()
            } else if call.method == "hideTab" {
                // 3. 隐藏TabBar
                self?.hideTab()
            } else {
                result(FlutterMethodNotImplemented)
            }
        })
    }
    
    /// 显示TabBar
    func showTab() {
        self.parent?.tabBarController?.tabBar.isHidden = false
    }
    /// 隐藏TabBar
    func hideTab() {
        self.parent?.tabBarController?.tabBar.isHidden = true
    }

}
